#! /usr/bin/env python
# -*- coding: utf-8 -*-

#======================================= init =================================

import sqlite3

tabname = 'host_name'
dbfile = 'host_name.db'

#初始化
def init():
    existTabSql = 'select count(*) from sqlite_master where type = "table" and name = "%s"' % tabname
    createTabSql = 'create table %s(id integer primary key autoincrement, host varchar(50) not null, domain varchar(50) not null, comment varchar(50) not null)' % tabname
    con = sqlite3.connect(dbfile)
    cur = con.cursor()
    cur.execute(existTabSql)
    existstatus = cur.fetchone()[0]
    if not existstatus:
        cur.execute(createTabSql)
        con.commit()
    con.close()

#======================================= dao ==================================

#执行事务性操作
def execute(sql):
    con = sqlite3.connect(dbfile)
    cur = con.cursor()
    cur.execute(sql)
    con.commit()
    con.close()
    
#执行查询操作
def fetch(sql):
    con = sqlite3.connect(dbfile)
    cur = con.cursor()
    cur.execute(sql)
    data = cur.fetchall()
    con.close()
    return data

#======================================= mode =================================

class dns:
    
    """Dns对象"""
    
    method = ''
    actionName = ''
    message = ''
    password = ''
    data = []
    
    id = 0
    host = ''
    domain = ''
    comment = ''
    
    def __init__(self):
        pass
    
    def setData(self):
        sql = 'select * from %s' % tabname
        self.data = fetch(sql)
        
    def setActionName(self):
        actionNameList = {'sel' : '查询', 'add' : '新增', 'mod' : '修改', 'dis' : '删除'}
        self.actionName = actionNameList[self.method]

#======================================= service ==============================

#======================================= action ===============================

import web, re, os

urls = (
    '/go/', 'go',
    '/add/', 'add',
    '/sel/', 'sel',
    '/dis/', 'dis',
    '/mod/', 'mod',
    '/.*', 'sel'
)
app = web.application(urls, locals())
render = web.template.render('templates/')

#更新配置文件的Dns
def modConfFile(d):
    conffile = 'host_name'
    d.setData()
    f = open(conffile, 'w')
    for conf in d.data:
        f.write('%s\t%s\r\n' % (conf[1], conf[2]))
    f.close()
    os.system('/etc/init.d/dnsmasq restart')

#检验输入信息
def checkInput(d):
    innerPassword = 'david' #内置密码
    i = web.input(id = '', host = '', domain ='', comment = '', password = '', method = 'add')
    status = 1
    #检测密码
    if not i.password == innerPassword:
        d.message = '密码验证错误'
        status = 0
    elif re.match('(\d+\.){3}\d+', i.host, re.I) == None:
        d.message = '地址输入错误'
        status = 0
    elif re.match('([a-z0-9]+\.)+[a-z0-9]+', i.domain, re.I) == None:
        d.message = '域名输入错误'
        status = 0
    return status

#获取Dns对象
def getDns():
        d = dns()
        i = web.input(id = '', host = '', domain ='', comment = '', password = '', method = 'add')
        d.id, d.host, d.domain, d.comment, d.password, d.method = i.id, i.host, i.domain, i.comment, i.password, i.method
        d.setActionName()
        return d

class go:
    """跳转操作 """
    def GET(self):
        d = getDns()
        d.setData()
        return render.view(d)

class sel:
    """查询操作 """
    def GET(self):
        d = getDns()
        d.setData()
        return render.view(d)    
    
    def POST(self):
        d = getDns()
        d.setData()
        return render.view(d)  
    
class add:
    """新增操作 """
    def POST(self):
        d = getDns()
        if checkInput(d):
            sql = 'insert into %s values(null, "%s", "%s", "%s")' % (tabname, d.host, d.domain, d.comment)
            execute(sql)
            d.message = '新增成功'
            modConfFile(d)
        else:
            d.setData()
        return render.view(d)
    
class mod:
    """修改操作 """
    def POST(self):
        d = getDns()
        if checkInput(d):
            sql = 'update %s set host = "%s", domain = "%s", comment = "%s" where id = %s' % (tabname, d.host, d.domain, d.comment, d.id)
            execute(sql)
            d.message = '修改成功'
            modConfFile(d)
        else:
            d.setData()
        return render.view(d)
    
class dis:
    """删除操作 """
    def POST(self):
        d = getDns()
        if checkInput(d):
            sql = 'delete from %s where id = %s' % (tabname, d.id)
            execute(sql)
            d.message = '删除成功'
            modConfFile(d)
        else:
            d.setData()
        return render.view(d)

if __name__ == '__main__':
    init() #初始加载DB信息
    app.run()
